package cn.wolfcode.luowowo.search.util;

import cn.wolfcode.luowowo.search.query.SearchQueryObject;
import cn.wolfcode.luowowo.search.template.DestinationTemplate;
import cn.wolfcode.luowowo.search.template.StrategyTemplate;
import cn.wolfcode.luowowo.search.template.TravelTemplate;
import com.alibaba.fastjson.JSON;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;

import java.util.ArrayList;
import java.util.List;

public class ESSearchUtil {

    /**
     * 但条件查询
     * @param client
     * @param indexs
     * @param types
     * @param fields
     * @param qo
     * @return
     */
    public static SearchHit[] fullSearch(TransportClient client, String[] indexs, String[] types, String[] fields, SearchQueryObject qo){
        SearchResponse response = client.prepareSearch(indexs)
                .setTypes(types)
                .setQuery(QueryBuilders.multiMatchQuery(qo.getKeyword(), fields))
                .setFrom(qo.getStart())
                .setSize(qo.getPageSize())
                .get();
        return response.getHits().getHits();
    }

    public static <T> List<T> fullSearch(TransportClient client, String index, String type, String[] fields, SearchQueryObject qo, Class<T> clz){
        SearchResponse response = client.prepareSearch(index)
                .setTypes(type)
                .setQuery(QueryBuilders.multiMatchQuery(qo.getKeyword(), fields))
                .setFrom(qo.getStart())
                .setSize(qo.getPageSize())
                .get();

        SearchHit[] hits = response.getHits().getHits();
        List<T> list = new ArrayList<>();
        if(hits != null && hits.length >0){
            for (SearchHit hit : hits) {
                T  t = JSON.parseObject(hit.getSourceAsString(), clz);
                list.add(t);
            }
        }
        return list;
    }

    /**
     * 添加高亮条件
     * @param searchQuery
     */
    public static void withHighlight(NativeSearchQueryBuilder searchQuery, String... fieldNames){

        for (String fieldName : fieldNames) {
            HighlightBuilder.Field hfield= new HighlightBuilder.Field("content")
                    .preTags("<em style='color:red'>")
                    .postTags("</em>")
                    .fragmentSize(100);
            searchQuery.withHighlightFields(hfield);
        }
    }










}
